from proxies import mengdaili
from settings import settings
import requests


class ProxyType:
    MENGDAILI = 0


class ProxyPool:
    __instance = None

    def __new__(cls):
        if not cls.__instance:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self):
        self.__addresses = None

    @staticmethod
    def __get_addresses(proxy_type=ProxyType.MENGDAILI):
        ips = []
        if proxy_type == ProxyType.MENGDAILI:
            mendaili_settings = settings.PROXIES["mengdaili"]
            session = requests.Session()
            ips = []
            login_ok = mengdaili.login(session,
                                       mendaili_settings['urls']['login_url'],
                                       mendaili_settings['user']['username'],
                                       mendaili_settings['user']['password'])
            if login_ok:
                sign_ok = mengdaili.sign_in(session,
                                            mendaili_settings['urls']['signin_url'])
                if sign_ok:
                    mengdaili.get_pay_uid(session,
                                          mendaili_settings['urls']['pay_url'])
                    order_id = mengdaili.get_order(session,
                                                   mendaili_settings['urls']['order_url'])
                    ips = mengdaili.get_ips(session, order_id)
                else:
                    try:
                        order_id = mengdaili.get_order(session,
                                                       mendaili_settings['urls']['order_url'])
                        ips = mengdaili.get_ips(session, order_id)
                    except(Exception, ):
                        uid = mengdaili.get_pay_uid(session,
                                                    mendaili_settings['urls']['pay_url'],
                                                    mendaili_settings['pay_types'][0],
                                                    mendaili_settings['pay_dates'][1])
                        mengdaili.hb_pay(session,
                                         mendaili_settings['urls']['hb_py_url'], uid)
                        order_id = mengdaili.get_order(session,
                                                       mendaili_settings['urls']['order_url'])
                        mengdaili.get_ips(session, order_id)
                        ips = mengdaili.get_ips(session, order_id)
        return ips

    def get(self):
        if not self.__addresses:
            self.__addresses = self.__get_addresses()
            if not self.__addresses:
                return ""
        return self.__addresses.pop()


